import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { connect } from 'react-redux';
import { Button, Image, Text, Textarea, View } from '@tarojs/components';
import CommentImagePicker from '@/components/Comment/ImagePicker';
import CommentRate from '@/components/Comment/Rate';
import utils from '@/utils/index';
import {
  commentUploadImgServer,
  confirmTakeoutCommentServer,
  getCommentScoreTypeServer,
} from '@/services/comment';
import Imagelocation from '@/components/Imagelocation';
import CommentTip from '@/components/Comment/Tip';
import picAvatar from './img/avatar.jpg';

const takeoutScoreTextMap = [
  { label: '很差', value: 0 },
  { label: '还行', value: 50 },
  { label: '超棒', value: 100 },
];

const toast = (title, callback) => {
  callback = callback || (() => {});
  Taro.showToast({ title, icon: 'none', duration: 1000 });
  setTimeout(() => {
    callback();
  }, 1000);
};

const Takeout = ({ order = {}, dispatch }) => {
  //提交评价的数据
  const [state, updateState] = useState({
    org: {
      topicId: 0,
      content: '',
      orderId: '',
      imgUrls: '',
      scoreList: [],
    },
  });

  const [uploadMap, setUploadMap] = useState({});

  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
  };

  //初始化
  const init = async () => {
    state.org.topicId = order.storeId;
    state.org.orderId = order.id;
    const commentScoreTypeRes = await getCommentScoreTypeServer({ appId: 'thjs_takeout_org' });
    if (commentScoreTypeRes.code === '1') {
      state.org.scoreList = commentScoreTypeRes.content.map((item) => ({ ...item, score: 0 }));
    }
    if (order.dmMobile) {
      state['takeout'] = {
        appid: 'thjs_takout_horseman',
        topicId: order.dmMobile,
        score: '',
      };
    }
    setState(state);
  };

  useEffect(() => {
    order.id && init();
  }, [order]);

  //选择图片
  const handleImagePicker = (files) => {
    state.org.imgUrls = files.join(',');
    setState(state);
  };

  //评分
  const handleRate = (val, item) => {
    item.score = val;
    setState(state);
  };

  //外卖评分/满意度
  const handleTakeoutScore = (val) => {
    state.takeout.score = val;
    setState(state);
  };

  //评价内容
  const handleInput = (val) => {
    state.org.content = val.detail.value;
    setState(state);
  };

  //刷新订单列表
  const refreshOrderList = () => {
    dispatch({
      type: 'order/setRefreshOrderId',
      payload: order.id,
    });
  };

  //提交评价
  const confirm = async () => {
    let params = JSON.parse(JSON.stringify(state));
    if (params.org.scoreList.filter((item) => item.score == 0).length) {
      toast('您还没有为星级打分');
      return;
    }
    if (params.takeout && params.takeout.score === '') {
      toast('您还没有为骑手打分');
      return;
    }
    Taro.showLoading({ title: '提交中~', mask: true });
    let files = {};
    const imgUrls = params.org.imgUrls ? params.org.imgUrls.split(',') : [];
    for (let file of imgUrls) {
      if (!!uploadMap[file]) {
        //避免重复上传
        files[file] = uploadMap[file];
        continue;
      }
      const fileRes = await commentUploadImgServer(file);
      if (fileRes.code == 1 && fileRes.content) {
        files[file] = fileRes.content;
      }
    }
    setUploadMap({
      ...uploadMap,
      ...files,
    });
    params.org.imgUrls = Object.values(files).join(',');
    confirmTakeoutCommentServer(params).then((res) => {
      Taro.hideLoading();
      if (res.code == 1) {
        toast('提交成功', () => {
          utils.backWithRefreash();
          refreshOrderList();
        });
      } else {
        toast(res.message);
      }
    });
  };

  return (
    <View className="submitCommentPage">
      <View className="submitCommentContent">
        <CommentTip>您的好评，就是商家和骑手努力的动力！</CommentTip>
        <View className="part1">
          <View className="partContent">
            <View className="ques">您对商家/菜品满意吗？</View>
            {/*商家信息*/}
            {order.storeId && (
              <View className="shopInfo">
                <Imagelocation className="logo" src={order.storeLogo} type="shop" />
                <Text className="name">{order.storeName}</Text>
              </View>
            )}
            {/*评价打分*/}
            {state.org.scoreList.map((item) => (
              <View className="shopRate" key={item.scoreTypeId}>
                <CommentRate showText value={item.score} onChange={(val) => handleRate(val, item)}>
                  {item.name}
                </CommentRate>
              </View>
            ))}
            {/*评价内容*/}
            <Textarea
              className="textarea"
              onInput={handleInput}
              placeholder="从多个角度评价宝贝，可以帮助更多想买的人"
              maxlength={120}
            />
            {/*买家图片*/}
            <CommentImagePicker onChange={handleImagePicker} />
          </View>
        </View>
        {order.dmMobile && (
          <View className="part2">
            <View className="partContent">
              <View className="ques">您对骑手满意吗？</View>
              {/*满意度*/}
              <View className="userInfo flexMiddle">
                <Image src={picAvatar} className="avatar" />
                <View className="text flexMiddle">
                  <View>送达骑手：{order.dmName}</View>
                  <View>送达时间：{order.deliveryTime}</View>
                </View>
              </View>
              <View className="scoreList flexMiddle">
                {takeoutScoreTextMap.map((item) => (
                  <View
                    key={item.value}
                    className={
                      (state.takeout.score === item.value ? 'active' : '') +
                      ` flexMiddle score score${item.value}`
                    }
                    onClick={() => handleTakeoutScore(item.value)}
                  >
                    {item.label}
                  </View>
                ))}
              </View>
            </View>
          </View>
        )}
        <View className="part3 flexMiddle">
          <Button className="btn customePageBackgroundStyle flexMiddle" onClick={confirm}>
            提交评价
          </Button>
        </View>
      </View>
    </View>
  );
};

export default connect(() => ({}))(Takeout);
